package com.wxxymaker.edu.service;

import com.blade.ioc.annotation.Bean;
import com.blade.kit.CollectionKit;
import com.wxxymaker.edu.model.entity.CourseSpecialty;
import io.github.biezhi.anima.Anima;
import io.github.biezhi.anima.enums.OrderBy;
import io.github.biezhi.anima.page.Page;
import lombok.extern.slf4j.Slf4j;

/**
 * @AUTHOR soft
 * @DATE 2018/10/16 16:55
 * @DESCRIBE 课程所属专业service
 */
@Bean
@Slf4j
public class CourseSpecialtyService implements Service<CourseSpecialty> {

    public Page<CourseSpecialty> page(int page, int size) {
        Page<CourseSpecialty> page1 = Anima.select().from(CourseSpecialty.class)
                .order(CourseSpecialty::getTime, OrderBy.DESC)
                .page(page, size);
        if (CollectionKit.isNotEmpty(page1.getRows())) {
            return page1;
        }
        return null;
    }

    @Override
    public CourseSpecialty add(CourseSpecialty CourseSpecialty) {
        if (Anima.atomic(()-> {
            Integer integer = CourseSpecialty.save().asInt();
            if (integer > 0) {
                CourseSpecialty.setId(integer);
            }
        }).isRollback()) {
            return null;
        }
        return CourseSpecialty;
    }

    @Override
    public CourseSpecialty delete(Object pk) {
        CourseSpecialty courseSpecialty = byId(pk);
        if (courseSpecialty != null) {
            courseSpecialty.delete();
            return courseSpecialty;
        }
        return null;
    }

    @Override
    public boolean change(CourseSpecialty CourseSpecialty) {
        Integer id = CourseSpecialty.getId();
        if (id != null && id > 0) {
            return CourseSpecialty.update() > 0;
        }
        return false;
    }

    //删除学科
    public boolean cancel(int spid) {
        boolean rollback = Anima.atomic(() -> {
            Anima.delete().from(CourseSpecialty.class)
                    .where(CourseSpecialty::getId, spid)
                    .execute();
        }).catchException(e -> {
            log.error("删除学科失败！{}", e.getMessage());
        }).isRollback();
        return !rollback;
    }

    @Override
    public CourseSpecialty byId(Object pk) {
        return Anima.select().from(CourseSpecialty.class).byId(pk);
    }


}
